﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using BitPortal.Models;
using BitPortal.Business;
using BitPortal.Modules;
using BitPortal.Utils;
using System.Web.Security;

namespace BitPortal.Admin.Product.Product.Module
{
    public partial class ProductAddEdit : Controls.BaseAdminControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack && !X.IsAjaxRequest)
            {
                datetimeDisplay.SelectedDate = DateTime.Now;
            }
            cbCategory.Items.Clear();
            BindCategoryData(null, "");
            if (IsPostBack)
            {
                LoadProperty();
            }
        }

        protected void GetProperty(object sender, EventArgs e)
        {
            LoadProperty();
        }

        protected void btnInsert_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductInsert");
                if (cbCategory.SelectedIndex < 0)
                {
                    throw new Exception("Bạn chưa chọn nhóm sản phẩm!");
                }
                Models.Product p = new Models.Product()
                {
                    CategoryID = Convert.ToInt32(cbCategory.SelectedItem.Value),
                    Name = txtName.Text,
                    Description = txtDescription.Text,
                    Detail = txtContent.Text,
                    Manufactor = txtManufactor.Text,
                    Warranty = txtWarranty.Text,
                    DatetimeDisplay = Convert.ToDateTime(datetimeDisplay.SelectedDate),
                    SortOrder = Convert.ToInt64(txtSortOrder.Text),
                    ThumbImage = Thumbnail.TextFieldURL.Text,
                    Price = Convert.ToDecimal(txtPrice.Text),
                    OldPrice = Convert.ToDecimal(txtOldPrice.Text),
                    ProductCost = Convert.ToDecimal(txtCost.Text),
                    CallToPrice = ckCallToPrice.Checked,
                    Quallity = Convert.ToInt32(txtQuality.Text),
                    Width = Convert.ToDecimal(txtWidth.Text),
                    Height = Convert.ToDecimal(txtHeight.Text),
                    Length = Convert.ToDecimal(txtLength.Text),
                    Weight = Convert.ToDecimal(txtWeight.Text),
                    IsDiscount = ckIsDiscount.Checked,
                    IsNew = ckIsNew.Checked,
                    IsHot = ckIsHot.Checked,
                    IsEnabled = ckIsEnabled.Checked,
                    AllowOrder = ckAllowOrder.Checked,
                    Avaiabled = ckAvaiable.Checked,
                };
                //Seo
                p.Meta.MetaTitle = txtMetaTitle.Text;
                p.Meta.MetaKeyword = txtMetaKeyword.Text;
                p.Meta.MetaDescription = txtMetaDescription.Text;
                //Logs
                p.Logs.CreatingUser = p.Logs.EditingUser = (Membership.GetUser() == null) ? null : (Guid?)new Guid(Membership.GetUser().ProviderUserKey.ToString());
                p.Logs.DatetimeCreated = p.Logs.DatetimeEdited = DateTime.Now;
                //Properties
                foreach (Models.ProductPropertyValue propertyValue in GetPropertyValue())
                {
                    p.ProductPropertyValues.Add(propertyValue);
                }
                //
                if (p.Insert() > 0)
                {
                    (this.Page as Controls.BaseAdminPage).ShowNotification("Thêm sản phẩm thành công!");
                    Window1.Hide();
                    ReloadTargetData();
                }
            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message);
            }
        }

        public void LoadProperty(long? productId = null)
        {
            //Panel5.ContentControls.Add(new Ext.Net.Checkbox() { ID = "property0", FieldLabel = "Test 2" });
            Panel5.ContentControls.Clear();
            //Panel5.Render();
            var list1 = Business.ProductPropertyBLL.GetByCondition(applyToAllProduct: true).ToList();
            var list2 = Business.ProductPropertyBLL.GetByCondition(cbCategory.SelectedItem.Value).ToList();
            foreach (Models.ProductProperty property in list1.Union(list2))
            {
                Models.ProductPropertyValue value;
                switch (property.DataType)
                {
                    case "Boolean":
                        Ext.Net.Checkbox control = new Ext.Net.Checkbox() { };
                        control.ID = "property" + property.PropertyID;
                        if (productId != null)
                        {
                            value = property.ProductPropertyValues.SingleOrDefault(ent => ent.ProductID == (long)productId);
                            if (value != null)
                            {
                                control.Checked = value.Value.Equals("True") ? true : false;
                            }
                        }
                        else
                        {
                            control.Checked = property.DefaultValue.Equals("True") ? true : false;
                        }
                        control.FieldLabel = property.Name;
                        //control.Render(Panel5, RenderMode.AddTo);
                        Panel5.ContentControls.Add(control);
                        break;
                    case "String":
                        Ext.Net.TextField control1 = new Ext.Net.TextField() { };
                        //control1.Width = new Unit(700);
                        control1.ID = "property" + property.PropertyID;
                        if (productId != null)
                        {
                            value = property.ProductPropertyValues.SingleOrDefault(ent => ent.ProductID == (long)productId);
                            if (value != null)
                            {
                                control1.Text = value.Value;
                            }
                        }
                        else
                        {
                            control1.Text = property.DefaultValue;
                        }
                        control1.FieldLabel = property.Name;
                        //control1.Render(Panel5, RenderMode.AddTo);
                        Panel5.ContentControls.Add(control1);
                        break;
                    case "Text":
                        Ext.Net.HtmlEditor control2 = new Ext.Net.HtmlEditor() { };
                        // control2.Width = new Unit(700);
                        control2.ID = "property" + property.PropertyID;
                        if (productId != null)
                        {
                            value = property.ProductPropertyValues.SingleOrDefault(ent => ent.ProductID == (long)productId);
                            if (value != null)
                            {
                                control2.Text = value.Value;
                            }
                        }
                        else
                        {
                            control2.Text = property.DefaultValue;
                        }
                        control2.FieldLabel = property.Name;

                        //control2.Render(Panel5, RenderMode.AddTo);
                        Panel5.ContentControls.Add(control2);
                        break;
                    case "Interger":
                        Ext.Net.NumberField control3 = new Ext.Net.NumberField() { };
                        //control3.Width = new Unit(200);
                        control3.MinValue = 0;
                        control3.AllowDecimals = false;
                        control3.ID = "property" + property.PropertyID;
                        if (productId != null)
                        {
                            value = property.ProductPropertyValues.SingleOrDefault(ent => ent.ProductID == (long)productId);
                            if (value != null)
                            {
                                control3.Text = value.Value;
                            }
                        }
                        else
                        {
                            control3.Text = property.DefaultValue;
                        }
                        control3.FieldLabel = property.Name;
                        //control3.Render(Panel5, RenderMode.AddTo);
                        Panel5.ContentControls.Add(control3);
                        break;
                    case "Double":
                        Ext.Net.NumberField control4 = new Ext.Net.NumberField() { };
                        //control4.Width = new Unit(200);
                        control4.MinValue = 0;
                        control4.ID = "property" + property.PropertyID;
                        if (productId != null)
                        {
                            value = property.ProductPropertyValues.SingleOrDefault(ent => ent.ProductID == (long)productId);
                            if (value != null)
                            {
                                control4.Text = value.Value;
                            }
                        }
                        else
                        {
                            control4.Text = property.DefaultValue;
                        }
                        control4.FieldLabel = property.Name;

                        //control4.Render(Panel5, RenderMode.AddTo);
                        Panel5.ContentControls.Add(control4);
                        break;
                    case "Datetime":
                        Ext.Net.DateField control5 = new Ext.Net.DateField() { };
                        //control5.Width = new Unit(200);
                        control5.ID = "property" + property.PropertyID;
                        if (productId != null)
                        {
                            value = property.ProductPropertyValues.SingleOrDefault(ent => ent.ProductID == (long)productId);
                            if (value != null)
                            {
                                control5.Text = value.Value;
                            }
                        }
                        else
                        {
                            control5.Text = property.DefaultValue;
                        }
                        control5.FieldLabel = property.Name;

                        //control5.Render(Panel5, RenderMode.AddTo);
                        Panel5.ContentControls.Add(control5);
                        break;
                }
            }

        }

        protected void btnUpdate_Click(object sender, DirectEventArgs e)
        {
            try
            {
                PermissionBLL.CheckRoleThrowException("ProductEdit");
                if (cbCategory.SelectedIndex < 0)
                {
                    throw new Exception("Bạn chưa chọn nhóm sản phẩm!");
                }
                ExtendedBitPortalEntities bitEnt = new ExtendedBitPortalEntities();
                long Id = Convert.ToInt64(txtID.Text);
                Models.Product p = bitEnt.Products.SingleOrDefault(ent => ent.ProductID == Id);
                if (p != null)
                {
                    p.CategoryID = Convert.ToInt32(cbCategory.SelectedItem.Value);
                    p.Name = txtName.Text;
                    p.Description = txtDescription.Text;
                    p.Detail = txtContent.Text;
                    p.Manufactor = txtManufactor.Text;
                    p.Warranty = txtWarranty.Text;
                    p.DatetimeDisplay = Convert.ToDateTime(datetimeDisplay.SelectedDate);
                    p.SortOrder = Convert.ToInt64(txtSortOrder.Text);
                    p.ThumbImage = Thumbnail.TextFieldURL.Text;
                    p.Price = Convert.ToDecimal(txtPrice.Text);
                    p.OldPrice = Convert.ToDecimal(txtOldPrice.Text);
                    p.ProductCost = Convert.ToDecimal(txtCost.Text);
                    p.CallToPrice = ckCallToPrice.Checked;
                    p.Quallity = Convert.ToInt32(txtQuality.Text);
                    p.Width = Convert.ToDecimal(txtWidth.Text);
                    p.Height = Convert.ToDecimal(txtHeight.Text);
                    p.Length = Convert.ToDecimal(txtLength.Text);
                    p.Weight = Convert.ToDecimal(txtWeight.Text);
                    p.IsDiscount = ckIsDiscount.Checked;
                    p.IsNew = ckIsNew.Checked;
                    p.IsHot = ckIsHot.Checked;
                    p.IsEnabled = ckIsEnabled.Checked;
                    p.AllowOrder = ckAllowOrder.Checked;
                    p.Avaiabled = ckAvaiable.Checked;
                    //Seo
                    p.Meta.MetaTitle = txtMetaTitle.Text;
                    p.Meta.MetaKeyword = txtMetaKeyword.Text;
                    p.Meta.MetaDescription = txtMetaDescription.Text;
                    //Logs
                    p.Logs.CreatingUser = p.Logs.EditingUser = (Membership.GetUser() == null) ? null : (Guid?)new Guid(Membership.GetUser().ProviderUserKey.ToString());
                    p.Logs.DatetimeCreated = p.Logs.DatetimeEdited = DateTime.Now;
                    //Properties
                    p.ProductPropertyValues.Clear();
                    foreach (Models.ProductPropertyValue propertyValue in GetPropertyValue())
                    {
                        p.ProductPropertyValues.Add(propertyValue);
                    }
                    //
                    if (bitEnt.SaveChanges() > 0)
                    {
                        (this.Page as Controls.BaseAdminPage).ShowNotification("Sửa sản phẩm thành công!");
                        Window1.Hide();
                        ReloadTargetData();
                    }
                }
            }
            catch (Exception ex)
            {
                (this.Page as Controls.BaseAdminPage).ShowMessage(ex.Message);
            }
        }

        public void BindCategoryData(BitPortal.Models.ProductCategory parent, string prefix)
        {
            foreach (BitPortal.Models.ProductCategory ac in ProductCategoryBLL.GetChilds(parent))
            {
                cbCategory.Items.Add(new Ext.Net.ListItem(prefix + " " + ac.Name, ac.CategoryID.ToString()));
                BindCategoryData(ac, prefix + "----");
            }
        }

        public List<Models.ProductPropertyValue> GetPropertyValue()
        {
            List<Models.ProductPropertyValue> listPropertyValues = new List<Models.ProductPropertyValue>();
            foreach (var c in Panel5.ContentControls)
            {
                switch (c.GetType().Name)
                {
                    case "Checkbox":
                        Ext.Net.Checkbox ck = (Ext.Net.Checkbox)c;
                        Models.ProductPropertyValue property = new Models.ProductPropertyValue()
                        {
                            PropertyID = Convert.ToInt32(ck.ID.Substring(8)),
                            Value = ck.Checked.ToString()
                        };
                        listPropertyValues.Add(property);
                        break;
                    case "TextField":
                        Ext.Net.TextField tf = (Ext.Net.TextField)c;
                        Models.ProductPropertyValue property2 = new Models.ProductPropertyValue()
                        {
                            PropertyID = Convert.ToInt32(tf.ID.Substring(8)),
                            Value = tf.Text
                        };
                        listPropertyValues.Add(property2);
                        break;
                    case "HtmlEditor":
                        Ext.Net.HtmlEditor ed = (Ext.Net.HtmlEditor)c;
                        Models.ProductPropertyValue property3 = new Models.ProductPropertyValue()
                        {
                            PropertyID = Convert.ToInt32(ed.ID.Substring(8)),
                            Value = ed.Text
                        };
                        listPropertyValues.Add(property3);
                        break;
                    case "NumberField":
                        Ext.Net.NumberField nf = (Ext.Net.NumberField)c;
                        Models.ProductPropertyValue property4 = new Models.ProductPropertyValue()
                        {
                            PropertyID = Convert.ToInt32(nf.ID.Substring(8)),
                            Value = nf.Text
                        };
                        listPropertyValues.Add(property4);
                        break;
                }
            }
            return listPropertyValues;
        }

        public void BindData(long? productID = null)
        {
            if (productID == null)
            {
                txtID.Text = txtSortOrder.Text = txtPrice.Text = txtOldPrice.Text = txtCost.Text = txtWidth.Text = txtLength.Text = txtHeight.Text =
                    txtWeight.Text = "0";

                txtName.Text = txtDescription.Text = txtManufactor.Text = txtWarranty.Text = Thumbnail.TextFieldURL.Text =
                    txtContent.Text = txtMetaTitle.Text = txtMetaKeyword.Text = txtMetaDescription.Text = "";

                ckCallToPrice.Checked = ckIsDiscount.Checked = ckIsHot.Checked = ckIsNew.Checked = false;
                ckIsEnabled.Checked = ckAllowOrder.Checked = ckAvaiable.Checked = true;

                btnInsert.Hidden = false;
                btnUpdate.Hidden = true;
                Window1.Title = "Thêm sản phẩm";
                Window1.Show();
                return;
            }
            Models.Product p = Business.ProductBLL.GetByID((long)productID);
            if (p != null)
            {
                txtID.Text = p.ProductID.ToString();

                txtName.Text = p.Name;
                txtDescription.Text = p.Description;
                txtContent.Text = p.Detail;
                txtManufactor.Text = p.Manufactor;
                txtWarranty.Text = p.Warranty;
                datetimeDisplay.SelectedDate = (p.DatetimeDisplay == null) ? DateTime.Now : (DateTime)p.DatetimeDisplay;
                txtSortOrder.Text = p.SortOrder.ToString();
                Thumbnail.TextFieldURL.Text = p.ThumbImage;
                txtPrice.Text = p.Price.ToString();
                txtOldPrice.Text = p.OldPrice.ToString();
                txtCost.Text = p.ProductCost.ToString();
                ckCallToPrice.Checked = p.CallToPrice;
                txtQuality.Text = p.Quallity.ToString();
                txtWidth.Text = p.Width.ToString();
                txtHeight.Text = p.Height.ToString();
                txtLength.Text = p.Length.ToString();
                txtWeight.Text = p.Weight.ToString();
                ckIsDiscount.Checked = p.IsDiscount;
                ckIsNew.Checked = p.IsNew;
                ckIsHot.Checked = p.IsHot;
                ckIsEnabled.Checked = p.IsEnabled;
                ckAllowOrder.Checked = p.AllowOrder;
                ckAvaiable.Checked = p.Avaiabled;
                //Seo
                txtMetaTitle.Text = p.Meta.MetaTitle;
                txtMetaKeyword.Text = p.Meta.MetaKeyword;
                txtMetaDescription.Text = p.Meta.MetaDescription;
                //Logs
                p.Logs.EditingUser = (Membership.GetUser() == null) ? null : (Guid?)new Guid(Membership.GetUser().ProviderUserKey.ToString());
                p.Logs.DatetimeEdited = DateTime.Now;
                //Category
                cbCategory.SelectedItem.Value = p.CategoryID.ToString();
                //Property
                LoadProperty(p.ProductID);

                btnInsert.Hidden = true;
                btnUpdate.Hidden = false;
                Window1.Title = "Sửa sản phẩm";
                Window1.Show();
            }
        }
    }
}